<?php

class Galaxy {

	public static function add_galaxy($info) {
		$title = DB::esc($info['title']);
		$icon = DB::esc($info['icon']);
		$uid = $_SESSION['user']['uid'];
		$description = DB::esc($info['description']);

		$query = "INSERT INTO galaxy (title, uid, icon, description) VALUES ('$title', '$uid', '$icon', '$description')";
		if (DB::query($query)) {
			$gid = DB::getMySQLiObject()->insert_id;
			// put the current user into the chatuser table
			$query = "INSERT INTO chatuser (gid, uid) VALUES ('$gid','$uid')";
			if (DB::query($query)) {
				$info['gid'] = $gid;
				Galaxy::tag_galaxy($info);
				return $gid;
			}
		}
		return 0;
	}

        public static function update_galaxy($info) {
            $gid = (int) $info['gid'];
            $uid = $_SESSION['user']['uid'];
            $title = $info['title'];
            $nids  = explode(',', DB::esc($info['nids']));
            $pids = explode(",", DB::esc($info['pids']));
            $des = $info['des'];

            $query = "UPDATE galaxy SET title = '$title', description = '$dec', uid = '$uid'
					WHERE gid = '$gid' AND uid = '$uid'";
            if (DB::query($query)) { // editing is successful
                foreach ($pids as $pid) {
                    DB::query("DELETE FROM galaxy_post (gid, pid) VALUES ('$gid', '$pid')");
                }
                foreach ($nids as $nid) {
                    DB::query("DELETE FROM galaxy_nebula (gid, nid) VALUES ('$gid', '$nid')");
                }
                Galaxy::tag_galaxy($info);
                return $gid; // updating is done
            }
            else {
                return -3; // something is wrong
            }

        }

	public static function delete_galaxy($gid) {
		$gid = (int) $gid;
		$uid = $_SESSION['user']['uid'];
		if (DB::query("DELETE FROM galaxy WHERE uid = '$uid' AND gid = '$pid'")) {
			return 1;
		} else {
			return 0; // error ? either the galaxy does not exist any longer, or the user is not the creator of the galaxy
		}
	}

	public static function visit_galaxy($gid) {
		$uid = $_SESSION['user']['uid'];
		if (!DB::query("INSERT INTO recent_galaxy (gid, uid) VALUES ('$gid','$uid')")) {
			return DB::query("UPDATE recent_galaxy SET last_visit = CURRENT_TIMESTAMP WHERE gid = '$gid' AND uid = '$uid'");
		} else {
			return true;
		}
	}

	// link post / nebula to the given galaxy
	public static function tag_galaxy($info) {
		$gid = DB::esc($info['gid']);
		$pids = explode(",", DB::esc($info['pids']));
		$nids = explode(",", DB::esc($info['nids']));

		foreach ($pids as $pid) {
			DB::query("INSERT INTO galaxy_post (gid, pid) VALUES ('$gid', '$pid')");
		}
		foreach ($nids as $nid) {
			DB::query("INSERT INTO galaxy_nebula (gid, nid) VALUES ('$gid', '$nid')");
		}
		return 1;
	}

	public static function mark_galaxy($gid) {
		$gid = (int) $gid;
		$uid = $_SESSION['user']['uid'];
		return DB::query("INSERT INTO mark_galaxy (uid, gid) VALUES ('$uid', '$gid')");
	}

	public static function unmark_galaxy($gid) {
		$gid = (int) $gid;
		$uid = $_SESSION['user']['uid'];
		return DB::query("DELETE FROM mark_galaxy WHERE uid = '$uid' AND gid = '$gid'");
	}

	public static function all_galaxies() {
		$query = "SELECT gid, title, uid, gts, description, icon, pids, GROUP_CONCAT( galaxy_nebula.nid ) AS nids
					FROM (
					SELECT gid, title, uid, galaxy.ts AS gts, description, icon, GROUP_CONCAT( galaxy_post.pid ) AS pids
					FROM galaxy
					LEFT JOIN galaxy_post
					USING ( gid ) 
					GROUP BY gid
					) gp 
					LEFT JOIN galaxy_nebula
					USING ( gid )
					GROUP BY gid";
		$result = DB::query($query);
		$galaxies = array();
		$mg_flag = get_magic_quotes_gpc();
		while ($galaxy = $result->fetch_object()) {
			$galaxy->title  = stripslashes( $galaxy->title );
			$galaxy->score = Galaxy::total_score($galaxy->gid);
			$galaxies[] = $galaxy;
		}
		return $galaxies;
	}

	public static function rate_galaxy($gid, $rate) {
		$uid = $_SESSION['user']['uid'];
		$gid = DB::esc($gid);
		$rate = DB::esc($rate);
		if ($rate != "-1" && $rate != "1") {
			return -1;
		}

		if (Galaxy::rated_by_uid($gid, $uid) == 0) {
			// this post has not been rated by the current user
			$query = "INSERT INTO galaxy_score (gid, uid, score) VALUES ('$gid', '$uid', '$rate')";
            if (DB::query($query)) {
                return 1;
            } else {
                return 0;
            }
		} else {
			return 2;
		}

		
	}

	// returns -1, 0(unrated), 1
	public static function rated_by_uid($gid, $uid) {
		$gid = DB::esc($gid);
		$uid = DB::esc($uid);

		$query = "SELECT score FROM galaxy_score WHERE gid = '$gid' AND uid = '$uid'";
		$res = DB::query($query);
		if ($res->num_rows) {
			return $res->fetch_object()->score;
		} else {
			return 0;
		}
	}

	// get the total score for the given gid
	public static function total_score($gid) {
		$gid = DB::esc($gid);
		$query = "SELECT SUM(score) AS score, COUNT(uid) AS count FROM galaxy_score WHERE gid = '$gid' GROUP BY gid";
		$res = DB::query($query);
		if ($res->num_rows) {
			return $res->fetch_object();
		} else {
			return 'null'; // not rated yet
		}
	}

	// this is for test purpose. dont use it if you know what is this
	public static function galaxies_for_uid($uid) {
		$uid = DB::esc($uid);
		$query = "SELECT gid, title, cuts, description, icon, pids, GROUP_CONCAT( galaxy_nebula.nid ) AS nids
					FROM (
					SELECT gid, title, description, cuts, icon, GROUP_CONCAT( galaxy_post.pid ) AS pids
					FROM (
					     SELECT gid, title, galaxy.uid, chatuser.ts AS cuts, toshow, icon, description 
						  FROM galaxy 
						  JOIN chatuser
						  USING(gid) WHERE chatuser.uid = '$uid' AND toshow = 'true'
						  ) chatusers
						  LEFT JOIN galaxy_post
						  USING ( gid ) 
						  GROUP BY gid
					) gp 
					LEFT JOIN galaxy_nebula
					USING ( gid )
					GROUP BY gid";
		$result = DB::query($query);
		$galaxies = array();
		$mg_flag = get_magic_quotes_gpc();
		while ($galaxy = $result->fetch_object()) {
			$galaxy->title  = stripslashes( $galaxy->title );
			$galaxy->score = Galaxy::total_score($galaxy->gid);
			$galaxies[] = $galaxy;
		}
		return $galaxies;
	}

	public static function galaxies_for_user_profile($uid) {
		$uid = DB::esc($info);
		$query = "SELECT gid, title, description, icon, chatuser.ts, toshow AS join_ts FROM chatuser JOIN galaxy USING(gid) WHERE chatuser.uid = '$uid' AND toshow = 'true' ORDER BY chatuser.ts DESC";
		$result = DB::query($query);
		$galaxies = array();
		$mg_flag = get_magic_quotes_gpc();
		while ($galaxy = $result->fetch_object()) {
			$galaxy->title  = stripslashes( $galaxy->title );
			$galaxies[] = $galaxy;
		}
		return $galaxies;
	}

	public static function galaxies_namecard_info($uid, $nid){
		$uid = DB::esc($uid);
		$nid = DB::esc($nid);
		$uid_from = $_SESSION['user']['uid'];
		$query = "SELECT nebula.nid AS nid,name,icon,user_nebula.uid AS uid FROM nebula
                    JOIN user_nebula
                    ON (user_nebula.nid=nebula.nid)
                    WHERE user_nebula.uid = '$uid'";
		$result = DB::query($query);
		$vector = DB::query("SELECT prof_vector FROM user WHERE uid='$uid'");
		$infos = array();
		while($info = $result->fetch_object()){
			$infos[] = $info;
		}
		$circled = DB::hasData("SELECT fid FROM circle WHERE uid_from='$uid_from' AND uid_to='$uid' AND nid='$nid'");
		return array(
				'data' => $infos,
				'circled' => $circled,
				'profv' => $vector->fetch_object()
		);
	}
	
	public static function join_galaxy($gid) {
		$gid = DB::esc($gid);
		$uid = $_SESSION['user']['uid'];
		if (DB::hasdata("SELECT gid FROM chatuser WHERE gid = '$gid' AND uid = '$uid' AND toshow = 'true'")) {
			return 0;
		}
		$query = "INSERT INTO chatuser (gid, uid) VALUES ('$gid','$uid')";
		if (DB::query($query)) {
			if (!DB::query("INSERT INTO recent_galaxy (gid, uid) VALUES ('$gid','$uid')")) {
				DB::query("UPDATE recent_galaxy SET last_visit = CURRENT_TIMESTAMP WHERE gid = '$gid' AND uid = '$uid'");
			}
			return array(
					'log' => 1,
					'rated' => DB::hasdata("SELECT gid FROM galaxy_score WHERE gid = '$gid' AND uid = '$uid'")
			);
		} else {
			return DB::query("UPDATE chatuser SET toshow = 'false' WHERE gid = '$gid' AND uid = '$uid'");
		}
	}

	public static function quit_galaxy($gid) {
		$gid = DB::esc($gid);
		$uid = $_SESSION['user']['uid'];
		$query = "UPDATE chatuser SET toshow = 'false' WHERE gid = '$gid' AND uid = '$uid'";
		if (DB::query($query)) {
			return 1;
		} else {
			return 0;
		}
	}

	// get the list of users in a certain galaxy
	public static function galaxy_users($gid) {
		if( !isset($_SESSION['user']) ) {
			return -1;
		}
		$uid = $_SESSION['user']['uid'];
		$gid = (int) $gid;
		$query = "SELECT user.uid, username, avatar, chatuser.ts AS ts, ouid IS NOT UNKNOWN AS online, blocked IS NOT UNKNOWN AS blocked
					FROM chatuser
					JOIN user
					USING ( uid ) 
					JOIN galaxy
					USING ( gid ) 
					LEFT JOIN online_user ON ( user.uid = online_user.uid )
					LEFT JOIN (SELECT uid_to, true AS blocked FROM blocked_user WHERE uid_from = '$uid') bu ON ( uid_to = chatuser.uid )
					WHERE chatuser.toshow = 'true' AND gid = '$gid'
					ORDER BY online DESC";
		$result = DB::query($query);
		$users = array();
		while ($user = $result->fetch_object()) {
			$users[] = $user;
		}
		return array(
			'data' => $users,
			'gid' => $gid
		);
	}
	
	public static function recent_galaxies($num,$uid) {
		$uid = DB::esc($uid);
		$query = "
			SELECT gid, recent_galaxy.uid AS uid, galaxy.uid AS galaxy_uid, title,
                   galaxy.description AS description, galaxy.ts AS ts, username, avatar FROM recent_galaxy
            JOIN galaxy USING(gid)
            JOIN user ON(user.uid = galaxy.uid)
			WHERE recent_galaxy.uid = '$uid'
			ORDER BY last_visit DESC
			LIMIT 0, $num
			";
		$result   = DB::query($query);
		$galaxies = array();
		$mg_flag = get_magic_quotes_gpc();
		while ($galaxy = $result->fetch_object()) {
			$galaxy->title  = stripslashes( $galaxy->title );
			$galaxies[] = $galaxy;
		}
		return $galaxies;
	}
}

?>
